Ext.extend(avatar.module, {
	role : 'maker', 
	partyId : null,
	getRole : function(index){
	   var role = "maker";
	   if (index == 1)
	   {  
		   role = "carrier";
	   } else if (index ==2)
	   {  
		   role = "salesman";
	   } else if (index == 3)
	       role = "payer";
	   return role;
	},
	sumStr : function(store, property){
		var rs = store.data.items, v = 0,
        start = 0;
        end = rs.length-1;

        for(var i = start; i <= end; i++){
            v += (parseInt(rs[i].data[property]) || 0);
        }
        return v;
	},
	init : function() {
        var me = this;
        var store = new Ext.data.JsonStore({
			fields : ["id", "name", "phoneNumber", "active"]
		}),
		month_report_ds = new Ext.data.JsonStore({
			fields : ["date","amount","att1","att2","att3", "att4"]
		}),
		rule_ds = new Ext.data.JsonStore({
			fields : ["effectiveTime", "className", "parameters", "createdTime"]
		}),
		product_ds = new Ext.data.JsonStore({
			fields : ["id", "name", "price"]
		});

		store.on('update', function(self, record){
			var role_filter = Ext.getCmp('party-role-filter');
			var updatedRec =  {id : record.get("id"), name : record.get("name"), 
			                   phoneNumber: record.get('phoneNumber'), 
			                   role : me.getRole(role_filter.selectedIndex), active: record.get('active')}; 	
			PartyManager.saveParty(updatedRec, function(data){			
			    role_filter.fireEvent('select', null, null, role_filter.selectedIndex);
			});

		});
		var Party = Ext.data.Record.create([
			{ name: 'name', type: 'string' },
			{ name: 'phoneNumber', type: 'string' }		
		]);

        var tbar = 
				 ['角色: ', ' ',
                   new Ext.ux.SelectBox({
                     listClass:'x-combo-list-small',
                     width:93,
                     value:'',
                     id:'party-role-filter',
                     store: new Ext.data.SimpleStore({
                        fields: ['role'],
                        expandData: true,
                        data : [ '生产班组','运输班组','销售员', '收款人']
                     }),
                     displayField: 'role',
					 listeners: {
                       select: function(self, rec,index){
                           me.role = me.getRole(index);
                           if (me.role != 'payer')
                             Ext.getCmp('party-change-password').hide();
                           else {
                             Ext.getCmp('party-change-password').show();
                             Ext.getCmp('party-change-password').setDisabled(true);
                           }
                          // if (Ext.getCmp('party-add-btn').disabled)
                           Ext.getCmp('party-add-btn').setDisabled(false);
                           PartyManager.getAllPartyByRole(me.role, function(data){
								store.loadData(data);
							});
						var g = Ext.getCmp('month-accounting-report-grid'),
						cm = g.getColumnModel();
						g.getStore().removeAll();
						
							if (me.role == 'maker'){								
								cm.setColumnHeader(3, '生产单号');								
								cm.setColumnHeader(4, '总条数');								
							} else {
								cm.setColumnHeader(3, '销售单号');								
								cm.setColumnHeader(4, '客户');																						
							} 	
							
							cm.setHidden(5, me.role == 'payer');
							cm.setHidden(6, me.role != 'salesman');	
						
						var g1 = Ext.getCmp('accounting-user-grid');
						   cm1 = g1.getColumnModel();
						
						   cm1.setHidden(3, me.role == 'payer');
						   
						}

					 }
                   }), ' ',
                   new Ext.Toolbar.Button({ id: 'party-add-btn', text:'新建', disabled:true, handler : function(){ 				   
				   		var p = new Party({
							name: '新用户',
							active: true
						});
						editor.stopEditing();						
						store.insert(0, p);
						var grid = Ext.getCmp('accounting-user-grid');
						grid.getView().refresh();
						grid.getSelectionModel().selectRow(0);
						editor.startEditing(0);	 

				   } }),
				    new Ext.Toolbar.Button({ id: 'party-change-password', text:'更改支付密码', hidden: true, disabled:true, handler : function(){ 				   
						editor.stopEditing();						 
                        var grid = Ext.getCmp('accounting-user-grid');
						var rec = grid.getSelectionModel().getSelected();
						var pwd_form = new Ext.form.FormPanel({
					     	autoWidth: true,
		            		labelWidth: 70, 
		            		layout:'form',
							frame:true, 
							defaultType: 'textfield', 				
			        		items : [		
			        		  {inputType: 'password', anchor: '96%', id:'old-password', fieldLabel : '当前密码'},
			        		  {inputType: 'password', anchor: '96%', id:'new-password', fieldLabel : '新密码'},
			        		  {inputType: 'password', anchor: '96%', id:'new-password2', fieldLabel : '新密码确认'}
			        		  ],
			        		 buttons: [
			        		  {text: '确定', handler: function() {
			        		      var oldPwd = Ext.getCmp('old-password').getValue(),
			        		          newPwd = Ext.getCmp('new-password').getValue(),
			        		          newPwd2= Ext.getCmp('new-password2').getValue();
			        		      if (rec.get('phoneNumber') !=null && oldPwd != rec.get('phoneNumber')){
			        		      	 alert('当前密码不正确。');
			        		      	 return;
			        		      }
			        		      if (newPwd == ''){
			        		      	alert('支付密码不能为空。');
			        		      	return;
			        		      }
			        		      if (newPwd === newPwd2){
			        		      		var updatedRec =  {id : rec.get("id"), name : rec.get("name"), 
						                   phoneNumber: newPwd, 
						                   role : 'payer', active: rec.get('active')}; 	
						                PartyManager.saveParty(updatedRec, function(d){
						                	alert('保存成功。');
						                	password_win.close();
						                	PartyManager.getAllPartyByRole(me.role, function(data){
												store.loadData(data);
											});
						                });	
			        		      }
			        		  	
			        		  	
			        		  	
			        		  }},
			        		  {text: '取消', handler: function() {password_win.close();} }
			        		 ]
						});
						var password_win = new Ext.Window({
						    constrain : true,
							layout : 'fit',
							width : 230,
							title: rec.get('name') + ' 更改支付密码',
							closeAction : 'close',
							height : 160,
							resizable : false,
							shadow : true,
							modal : true,
							closable : true,
							border : false,						
							items:[pwd_form]
						 });
			
						  password_win.show();			
						
				   } })  
			    ];
	   var editor = new Ext.ux.grid.RowEditor({
			saveText: '保存',
			cancelText: '取消',
			clicksToEdit: 2
		});

        var sm = new Ext.grid.RowSelectionModel({singleSelect:true});
        sm.on('selectionchange', function(sm){	
		    var record = sm.getSelected();
		
		    Ext.getCmp('check-month-accounting-btn').setDisabled(!record);
		    Ext.getCmp('add-accounting-rule-btn').setDisabled(!record || me.role != 'maker');
		    if (me.role == 'payer'){
		      Ext.getCmp('party-change-password').setDisabled(!record || record.get('name') == '新用户');
		    }
		    //refresh rule grid
		    if (record){
			    var id = record.get('id');
			    if (id != undefined){
			    	me.partyId = id;
				    PartyManager.getPartyById(id, function(party){
				        rule_ds.loadData(party.persistentRules);		    
				    });
			    }
		    } else {
		      rule_ds.removeAll(); 
		      me.partyId = null; 
		    }
		    
		    
		    
        });
        var today = new Date(),
		    year = today.getFullYear(),
            month = today.getMonth() + 1;
		this.tabpanel.add(
		 {	xtype:'panel',
		  	closable:true,
		  	id: 'accounting-users',
		  	title: '帐目用户',
		  	border: false,
			layout:'border',
			defaults: {
				split: true
			},
			items:[
		     {			
				xtype:'grid',
				region: 'center',
				margins: '2 0 2 2',
				id: 'accounting-user-grid',
				store : store, 
				sm : sm,
                tbar: tbar,
				plugins: [editor],
				columns:[
					new Ext.grid.RowNumberer(),
					{  dataIndex: 'id', hidden: true },
					{
					   header: '名称',
					   dataIndex: 'name',
					   sortable: true,
					   width: 200,
					   editor: {
							xtype: 'textfield',
							allowBlank: false
						}
					},{
						header: '联系电话',
						dataIndex: 'phoneNumber',
						width: 115,
						editor: {
							xtype: 'textfield'
						}
					},
					{
			            xtype: 'booleancolumn',
			            header: '可用',
			            dataIndex: 'active',
			            align: 'center',
			            width: 55,
			            trueText: '是',
			            falseText: '否',
			            editor: {
			                xtype: 'checkbox'
			            }
			        }
					]				
          },
          { xtype: 'tabpanel',
            margins: '2 2 2 2',
            id: 'accounting-tab',
            region: 'east',
            width: 475,
			activeTab: 0,
			items:[
              {			
				id: 'month-accounting-report-grid',	
				xtype:'grid',
				title:'历史帐目',
				enableHdMenu: false,
				store : month_report_ds,
				columns:[
					new Ext.grid.RowNumberer(),
					{xtype: 'datecolumn', format:'Y-m-d', header:'日期', width:82, dataIndex:'date'},
					{xtype: 'numbercolumn', header: '金额', width:68, dataIndex:'amount', format: '0.00'},
					{header: '销售单号', width:99, dataIndex:'att1'},
					{header: '客户', width:48, dataIndex:'att2'},
					{header: '总块数', width:48, dataIndex:'att3'},
					{header: '货款金额', width:66, dataIndex:'att4', hidden: true}
				], 
				tbar : 
				 [ '日期范围  ',
				   new Ext.form.ComboBox({
				 	    id:'accounting-range-mode',
						selectOnFocus : true,
						triggerAction : 'all',
						value : '按月',
						width: 50,
						forceSelection : true,
						editable : false,
						store : ["按月", "按日"],
						listeners : {
				           'select' : function(combo, rec, index){
				           	  Ext.getCmp('accounting-year-combo').setVisible(index == 0);
				           	  Ext.getCmp('accounting-month-combo').setVisible(index == 0);
				           	  Ext.getCmp('accounting-day').setVisible(index == 1);
				           
				           }
						}
				   }),
				   ' ',
				   new Ext.form.ComboBox({
				 	    id:'accounting-year-combo',
						selectOnFocus : true,
						triggerAction : 'all',
						value : year,
						width: 55,
						forceSelection : true,
						editable : false,
						store : ["2010", "2011", "2012", "2013", "2014", "2015", "2016"]}),
					{ xtype:'datefield',
				      id: 'accounting-day',
				      hidden: true,
				      format:'Y-n-j', value: new Date() }, ' ',	
					new Ext.form.ComboBox({
						id:'accounting-month-combo',
						selectOnFocus : true,
						triggerAction : 'all',
						value : '2',
						width: 40,
						forceSelection : true,
						editable : false,
						value: month,
						store : ['1', '2','3', '4', '5', '6', '7' ,'8', '9', '10', '11', '12']}),'-',
					{text:'统计',id:'check-month-accounting-btn',disabled:true,
					 handler: function(){
					 	var record = sm.getSelected(),
					 	    y = Ext.getCmp('accounting-year-combo').getValue(),
					 	    m = Ext.getCmp('accounting-month-combo').getValue(),
					 	    d = Ext.getCmp('accounting-day').getValue(),
					 	    mode = Ext.getCmp('accounting-range-mode').getValue();
					 	if (record){
					 		if (mode == '按月')
						 	  PartyManager.findAccountingEntriesByMonth(record.get('id'), y, m, function(data){
						 	    month_report_ds.loadData(data);   
						 	  });
						 	else
						 	  PartyManager.findAccountingEntriesByDay(record.get('id'), d, function(data){
						 	    month_report_ds.loadData(data); 						 	  
					 	      });	
					 	}
					 }					
					
					},'-'
					, {text:'打印', handler: function() { 
						var record = sm.getSelected(),
						    y = Ext.getCmp('accounting-year-combo').getValue(),
					 	    m = Ext.getCmp('accounting-month-combo').getValue();
					 	if (record){
						    var grid = Ext.getCmp('month-accounting-report-grid'),
						    ds = grid.getStore(), sum = ds.sum('amount'),
						    sum1 = 0, sum2 = 0, footer;
						    sum = Math.round(sum*100)/100;
						    //按角色统计
						    if (me.role == 'maker'){
						    	sum1 = me.sumStr(ds, 'att2'); //总条数
						    	sum2 = me.sumStr(ds, 'att3');//总块数
						    	footer = '总金额:' + sum + ' 总条数:'+sum1 + ' 总块数:'+sum2;
						    } else if (me.role == 'payer'){
						    	footer = '总金额:' + sum ;
						    } else {
						    	sum2 = me.sumStr(ds, 'att3');//总块数
						    	sum3 = me.sumStr(ds, 'att4'); //货款总额
						    	footer = '总金额:' + sum + ' 总块数:' + sum2 + ' 货款总额:' + sum3;						    	
						    }
						    var mode = Ext.getCmp('accounting-range-mode').getValue();
						    var title;
						    if (mode == '按月')
						      title = y + '年' + m + '月帐';
						    else
						      title = Ext.getCmp('accounting-day').getRawValue() + ' 帐';
						    printGrid(grid, title, record.get('name'), footer );
					 	}
					  }}
					]
          },{
          	xtype: 'grid',
          	title: '帐目规则',
          	
          	visibled: false,
          	store: rule_ds,
          	columns:[
					new Ext.grid.RowNumberer(),
					{xtype: 'datecolumn', format:'Y-m-d', header:'生效日期', width:70, dataIndex:'effectiveTime'},
					
					{header: '规则名称', width:130, dataIndex:'className', renderer: function(val){	
					     if (val == 'cc.avatar.model.rule.SaleCommisionPR')
					         return '总块数乘以提成单价';
					     if (val == 'cc.avatar.model.rule.ProduceCostPR')  
					         return '入库数量乘以产品单价';
					}},
					{header: '单价',width:55, dataIndex:'parameters', renderer: function(val){
					     if (val.indexOf('column') > -1){
					     	return val.substring(7) + " / 条";
					     }
					     if (val.indexOf('block') > -1){
					     	return val.substring(6) + " / 块";
					     }
					     return val;
						
					}},
					{xtype: 'datecolumn', format:'Y-m-d H:i', header: '记录时间', width:100, dataIndex:'createdTime'}
				],
			tbar : [{text:'新增', id:'add-accounting-rule-btn', disabled: true, handler: function(){
				
                ProductManager.getAllProduct(function(data){
                    product_ds.loadData(data);
                });
			    var form = new Ext.FormPanel({
		                labelWidth: 80, 
		                
	            		frame: true,
	            		autoHeight:true,
						defaults: {anchor: '98%'},
						defaultType: 'textfield', 				
		        		items : [	        		  
		        		  {xtype:'combo', fieldLabel:'规则', name: 'className',
		        		    id : 'party-rule-classname',
		        		     store : 
			                      new Ext.data.SimpleStore({
			                        fields: ['id', 'name'],
			                        data : me.role=='salesman'? [ ['cc.avatar.model.rule.SaleCommisionPR','总块数乘以提成单价'] ]:
			                           [ ['cc.avatar.model.rule.ProduceCostPR','入库数量乘以产品单价'] ]
			                     }),
			                 forceSelection : true,
					         displayField: 'name',
					         valueField:'id',
							 editable:false,
							 typeAhead: true,
							 mode: 'local',
							 value : me.role=='salesman'?'cc.avatar.model.rule.SaleCommisionPR':'cc.avatar.model.rule.ProduceCostPR',
							 triggerAction: 'all',
							 selectOnFocus:true,						 
							 allowBlank: false
			              },
			              {xtype:'datefield', id: 'party-rule-effectivedate', format:'Y-m-d',editable:false,
                           fieldLabel:'生效日期', name: 'effectiveTime', value : new Date()},
                          
		        		  {  xtype:'combo', 
                             id : 'party-rule-countby',
                             fieldLabel:'计价模式',
                             forceSelection : true,
							 editable:false,
							 typeAhead: true,
							 mode: 'local',
							 store: ['按块统计', '按条统计'],
							 value : '按块统计',
							 triggerAction: 'all',
							 hideLabel: me.role!='maker',
							 hidden: me.role!='maker',
							 selectOnFocus:true	},
							 	
						  {xtype:'numberfield', id: 'party-rule-price',fieldLabel:'单价', allowBlank: false}                 
                         ],
                         buttons: [{
			                    text:'提交',
			                    handler: function(){
			                    	var price = Ext.getCmp('party-rule-price');
	                    			if (!price.isValid()){
	                    				return;
	                    			}
	                    			var parameter = price.getValue();
			                    	var pr = new PostingRule();
			                    	pr.className = Ext.getCmp('party-rule-classname').getValue();                    			
	                    			pr.effectiveTime = Ext.getCmp('party-rule-effectivedate').getValue();		                    	
			                    	
	                    	        if (me.role == 'maker'){                                         
                                        var countBy = Ext.getCmp('party-rule-countby').getValue() == '按块统计'?'block':'column';
                                        parameter = countBy + "," + parameter;                                        
			                    	}
			                        pr.parameters = parameter;                    			
	                    			PartyManager.addRule(me.partyId, pr, function(data){
                    			  		PartyManager.getPartyById(me.partyId, function(party){		                    			  			
									        rule_ds.loadData(party.persistentRules);		    
									    });
	                    			});
            	
			                    	win.close();
			                    }
			                    },
			                    { text: '关闭',
			                      handler: function(){
			                        win.close();
			                    }
                         }]
		        		 				
			         });
			         
			         if (me.role!='maker'){
			         	
			         }
					   var win =  new Ext.Window({
						    constrain : true,
							layout : 'fit',
							title: '新增帐目规则',
							width : 400,
							autoHeight:true,
							closeAction : 'close',
							height: 400,
							resizable : false,
							shadow : true,
							modal : true,
							closable : true,
							border : false,
							animCollapse : true,
							items : [form]
							
						});
						
						win.show();

			}}]
          }
          ]
          }]
		 
          }).show();

	}
});

